export const handleSaveCurrentImage = async (url) => {
  const currentImage = url;
  if (!currentImage) {
	uni.showToast({ title: '图片不存在', icon: 'none' });
	return;
  }
  await saveImageToAlbum(currentImage);
};

const saveImageToAlbum = async (imageUrl) => {
  try {
	// 1. 获取图片信息
	const imageInfo = await getImageInfoWithRetry(imageUrl);
	console.log('path', imageInfo.path);
	// 2. 检查并请求相册权限
	const hasPermission = await checkPhotoAlbumPermission();
	if (!hasPermission) {
	  await requestPhotoAlbumPermission();
	}
	
	// 3. 保存图片
	await saveImageToPhotosAlbum(imageInfo.path);
	uni.showToast({ title: '保存成功', icon: 'success' });
	return true;
  } catch (error) {
	handleSaveImageError(error);
	return false;
  }
};

// 获取图片信息 重试机制
const getImageInfoWithRetry = (src, retries = 2) => {
  return new Promise((resolve, reject) => {
	const attempt = (remaining) => {
	  uni.getImageInfo({
		src,
		success: resolve,
		fail: (err) => {
		  if (remaining > 0) {
			attempt(remaining - 1);
		  } else {
			  console.error("src：", src);
			  console.error('获取图片信息失败', err)
			reject(new Error('获取图片信息失败'));
		  }
		}
	  });
	};
	attempt(retries);
  });
};

// 检查相册权限
const checkPhotoAlbumPermission = async () => {
  try {
	const setting = await new Promise(resolve => {
	  uni.getSetting({
		success: resolve,
		fail: () => resolve({})
	  });
	});
	return !!setting.authSetting?.['scope.writePhotosAlbum'];
  } catch {
	return false;
  }
};

// 请求相册权限
const requestPhotoAlbumPermission = async () => {
  const { confirm } = await new Promise(resolve => {
	uni.showModal({
	  title: '提示',
	  content: '需要授权访问相册才能保存图片',
	  success: resolve,
	  fail: () => resolve({ confirm: false })
	});
  });
}

// 保存到相册
const saveImageToPhotosAlbum = (filePath) => {
  return new Promise((resolve, reject) => {
	uni.saveImageToPhotosAlbum({
	  filePath,
	  success: resolve,
	  fail: reject
	});
  });
};

// 错误处理
const handleSaveImageError = (error) => {
  console.error('保存图片失败:', error);
  
  const messageMap = {
	'getImageInfo:fail': '获取图片信息失败',
	'saveImageToPhotosAlbum:fail auth deny': '无相册访问权限',
	'用户拒绝授权': '您拒绝了相册访问权限',
	'授权失败': '授权访问相册失败',
	'default': '保存图片失败，请重试'
  };
  
  const message = messageMap[error.message] || messageMap.default;
  uni.showToast({ title: message, icon: 'none' });
};


// 使用实例
// const handleSaveCurrentImage = async () => {
//   const currentImage = classList.value[currentIndx.value]?.picUrl;
//   if (!currentImage) {
// 	uni.showToast({ title: '图片不存在', icon: 'none' });
// 	return;
//   }
  
//   await saveImageToAlbum(currentImage);
// };